package com.cr.front.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cr.common.exception.ServiceException;
import com.cr.front.base.service.CaptchaService;
import com.cr.front.user.mapper.RoleMapper;
import com.cr.front.user.mapper.UserMapper;
import com.cr.front.user.mapper.UserRoleMapper;
import com.cr.front.user.pojo.dto.param.UserAddParam;
import com.cr.front.user.pojo.dto.param.UserUpdateParam;
import com.cr.front.user.pojo.entity.User;
import com.cr.front.user.pojo.entity.UserRole;
import com.cr.front.user.pojo.vo.LoginResultVO;
import com.cr.front.user.pojo.vo.UserDetailVO;
import com.cr.front.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private CaptchaService captchaService;

    private void checkPhoneNumExists(String PhoneNum, Long userId) {
        if (StrUtil.isEmpty(PhoneNum)) {
            throw new ServiceException("手机号码不能为空");
        }
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getPhoneNum, PhoneNum);
        queryWrapper.ne(userId != null, User::getId, userId);
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new ServiceException("手机号码已存在");
        }
    }
    @Override
    public LoginResultVO  insert(UserAddParam userAddParam) {

        captchaService.checkCaptcha(userAddParam.getCaptchaKey(),userAddParam.getCaptcha());

        //
        checkPhoneNumExists(userAddParam.getAccount(), null);
        //
        User user = new User();
//        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userAddParam, user);
        if (StrUtil.isEmpty(userAddParam.getPassword())) {
            throw new ServiceException("密码不能为空");
        }
        user.setPhoneNum(userAddParam.getAccount());
        user.setPassword(BCrypt.hashpw(userAddParam.getPassword()));
        user.setStatus(user.getStatus() == null ? 0 : user.getStatus());
        user.setNickname(user.getNickname() == null ? user.getPhoneNum() : user.getNickname());
        user.setCreateTime(new Date());
        user.setCreateBy(user.getNickname());
        user.setUpdateTime(new Date());
        user.setUpdateBy(user.getNickname());
        // 新增用户信息
        userMapper.insert(user);
        // 新增用户和角色关联
        insertUserRole(user.getId(), userAddParam.getRoleIds());

        // 查询用户的角色
        List<String> roles = roleMapper.selectRolesByUserId(user.getId());
        // 查询用户的权限
        List<String> perms = new ArrayList<>();
        perms.add("*");

        //Sa-Token 会话登录
        StpUtil.login(user.getId());


        //保存角色和权限到 Sa-Token 的session中,后期可以重复从里面拿roles和perms来使用
        StpUtil.getSession().set("roles",roles);
        StpUtil.getSession().set("perms",perms);
        StpUtil.getSession().set("nickname",user.getNickname());


        //构建登录结果VO对象
        LoginResultVO loginResultVO = new LoginResultVO();
        loginResultVO.setNickname(user.getNickname());
        loginResultVO.setAvatar(user.getAvatar());
        loginResultVO.setPerms(perms);
        loginResultVO.setToken(StpUtil.getTokenValue());


        // 返回登录结果VO对象
        return loginResultVO;


    }

    @Override
    public UserDetailVO selectById(Long id) {


        return getUserDetailVO(id);


    }

    @Override
    public UserDetailVO selectMyInfo() {
        long id;
        String obj = StpUtil.getLoginId().toString();
        if (obj != null) {
            id = Long.parseLong(obj);
        }else{
            return null;

        }
        return getUserDetailVO(id);

    }

    @Override
    public void updateUser(UserUpdateParam userUpdateParam) {
        long id;
        String obj = StpUtil.getLoginId().toString();
        if (obj != null) {
            id = Long.parseLong(obj);
        }else{
            throw new ServiceException("请先登录");
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setId(id);
        userMapper.updateById(user);
    }

    private UserDetailVO getUserDetailVO(Long id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            UserDetailVO userDetailVO = new UserDetailVO();
            BeanUtils.copyProperties(user, userDetailVO);
            userDetailVO.setRoleIds(userRoleMapper.selectRoleIdsByUserId(id));
            return userDetailVO;
        }
        return null;
    }

    private void insertUserRole(Long userId, List<Long> roleIds) {

        if (CollectionUtil.isNotEmpty(roleIds)) {
            List<UserRole> userRoleList = new ArrayList<>(roleIds.size());
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleList.add(userRole);
            }
            userRoleMapper.insertBatchUserRole(userRoleList);
        }
    }
}
